package com.vtech.mybatis.baseservice.util;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;

import java.util.Iterator;

/**
 * TODO
 *
 * @author houzhiwei
 * @date 2016/11/6 22:44.
 */
public class PluginUtil {
    public static String insertStr(int pos, String insertStr, String src) {
        src = src.substring(0, pos) + insertStr + src.substring(pos);
        return src;
    }

    //<include refid="Base_Column_List" />
    public static XmlElement getBaseColumnListElement(IntrospectedTable introspectedTable) {
        XmlElement answer = new XmlElement("include");
        answer.addAttribute(new Attribute("refid", introspectedTable.getBaseColumnListId()));
        return answer;
    }

    /**
     * 生成“<sql id="Base_Column_List" > ...   </sql>”
     *
     * @return xml元素
     */
    public static XmlElement generatorBaseColumnListElement(IntrospectedTable introspectedTable) {
        XmlElement sql = new XmlElement("sql");
        StringBuilder sb = new StringBuilder();
        sql.addAttribute(new Attribute("id", introspectedTable.getBaseColumnListId()));
        Iterator<IntrospectedColumn> iter = introspectedTable.getAllColumns().iterator();
        while (iter.hasNext()) {
            sb.append(MyBatis3FormattingUtilities.getSelectListPhrase(iter.next()));
            if (iter.hasNext()) {
                sb.append(", "); //$NON-NLS-1$
            }
            if (sb.length() > 80) {
                sql.addElement(new TextElement(sb.toString()));
                sb.setLength(0);
            }
        }
        if (sb.length() > 0) {
            sql.addElement((new TextElement(sb.toString())));
        }
        sb.setLength(0);
        return sql;
    }
}
